迴圈 for ..in


Posted by mijouhsieh on 2023-03-15

for ...in for...of foraEach Object.keys()

for(let 自訂變數key in 物件名稱) - 迭代物件的鍵(key)

const students =
[
  {name:a, math:10, science: 8, art: 6},
  {name: b, math: 12, science: 4, art:10}
]

let htmlContent = ' '
//迭代一個student 物件裡的鍵(key)
//情境1 分開名稱和分數 做不同的HTML結構

for (let score(key) in student(物件)) {
  if (score === "name") {
      htmlContent += '<div> ${student[score]} </div>'
  } else {
      htmlContent += '<div> ${student[score]} <i>...</i></div>'
  }
}

//情境2 分數加總

for (let score(key) in student(物件)) {
  if (student[score] !== undefined) 或
  if (typeof student[score] === 'number') {
      sum += student[score]
  } 
}

注意 typeof 會return字串,所以 ' 型別要加引號 '
typeof MDN


for...in 不要用在 迭代陣列元素

for...in 陣列

players.broken = "broken" 即 新增broken屬性,for...in迴圈會把它印出來!!!

for … in 在迭代陣列時,除了迭代陣列的 index,也會迭代陣列的其他屬性。

for...in 陣列

for…in MDN 文件中有個小節 Array iteration and for...in 建議:
若處理的只有 陣列裡的元素 (即整數 index 就可存取的那些元素,例如 array[0], array[1] 等等),沒有要處理陣列的其他屬性時,
=> 不要使用 for…in 來迭代
=> 使用 forEach, for…of 或傳統的 for loop


#for-loop #for-in #for-in DONT WITH Arr







Related Posts

Jump Diffusion Option Valuation in  Discrete Time

Jump Diffusion Option Valuation in Discrete Time

程式導師實驗計畫 FE102

程式導師實驗計畫 FE102

Custom HTML5 Video Player

Custom HTML5 Video Player


Comments